<template>
  <div style="width:100%;height:100%;">
    <a-button type="primary" @click="changeImg(false)">隐藏图标</a-button>｜｜
    <a-button type="primary" @click="changeImg(true)">显示图标</a-button>｜｜
    <a-button type="primary" @click="changePerson">更新位置</a-button>

    <h3>X:{{x}} Y:{{y}}</h3>
    <h3>X1:{{x1}} Y1:{{y1}}</h3>
    <div id="maps" class="map">
      <div id="popup" class="ol-popup">
        <a href="#" id="popup-closer" class="ol-popup-closer"></a>
        <div id="popup-content" class="popup-content"></div>
      </div>
    </div>
  </div>
</template>
<script>
import Point from "ol/geom/Point";
import { GeoJSON } from "ol/format";
import { defaults as interactionDefaults } from "ol/interaction";
import "ol/ol.css";

import { Circle as CircleStyle, Icon, Fill, Stroke, Style } from "ol/style";
import { getCenter } from "ol/extent";
import { defaults as defaultControls } from "ol/control";

import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Map, View, Feature, ol } from "ol";
// 投影
import { transform, get, fromLonLat, toLonLat } from "ol/proj";
import Overlay from "ol/Overlay";
const JSONURl = require("./JSON/4.json");
export default {
  data() {
    return {
      map: null,
      x: null,
      y: null,
      x1: null,
      y1: null,
      Icon: [
        { x: 2827.970491535012, y: 6871.263035307627, type: "1.png" },
        { x: 985.5882702715971, y: 3669.2510749397316, type: "2.png" },
        { x: 1618.7480305399586, y: 10292.284252992747, type: "p.png" },
      ],
      personIcon: [
        { x: 27.970491535012, y: 6871.263035307627, type: "p1.png" },
        { x: 485.5882702715971, y: 1269.2510749397316, type: "p1.png" },
        { x: 18.7480305399586, y: 10292.284252992747, type: "p1.png" },
      ],

      // JSONd图层
      vector: null,
      // 图标层
      vectorLayer: null,
      personLayer: null,
    };
  },
  mounted() {
    this.init();
    //添加JSON底图
    this.addJSON();
    //  添加弹框图层
    this.addPopup();
    // 添加小人图层
    this.personIocn();
    //

    // console.log(this.map);
  },
  methods: {
    // 初始化地图
    init() {
      // 动态增加图标

      //图层渲染的区域，即浏览器窗口中可见的地图区域。extent 是一个矩形范围，格式是[number, number, number, number] 分别代表 [left, bottom, right, top]为了提升渲染效率和加载速度，extent范围之外的瓦片是不会请求的，当然也不会渲染；
      let extent = [2, 5, 40, 20];
      this.map = new Map({
        view: new View({
          center: getCenter(extent),
          zoom: 12,
          // 最大放大倍数
          maxZoom: 14,
          // 最小缩放倍数
          minZoom: 10,
        }),
        controls: defaultControls({
          zoom: true,
        }).extend([]),
        // 图层 layers 配置图层的数据源
        layers: [],
        target: "maps",
      });
      this.map.on("pointermove", (e) => {
        // console.log(e.coordinate);
        this.x = e.coordinate[0];
        this.y = e.coordinate[1];
        this.x1 = transform(e.coordinate, "EPSG:3857", "EPSG:4326");

        // console.log(`x1-EPSG:4326:${this.x1},x1-EPSG:3857:${e.coordinate}`);
      });
      // this.map.addLayer(vector);
    },
    // 切换图标层
    changeImg(a) {
      if (a) {
        this.addIocn(this.Icon);
      } else {
        this.map.removeLayer(this.vectorLayer);
      }
    },
    /**
     * 第一种：点标记 marker
     * 创建一个标注信息
     */
    addMarker() {
      let extent = [2, 5, 40, 20];
      // 绘画图层
      var marker = new Overlay({
        position: getCenter(extent),
        positioning: "center-center",
        element: document.getElementById("marker"),
        stopEvent: false,
      });
      this.map.addOverlay(marker);
    },
    /**
     * 点击弹出框
     */
    addPopup() {
      // 使用变量存储弹窗所需的 DOM 对象
      var container = document.getElementById("popup");
      var closer = document.getElementById("popup-closer");
      var content = document.getElementById("popup-content");
      // 创建一个弹窗 Overlay 对象
      this.overlay = new Overlay({
        element: container, //绑定 Overlay 对象和 DOM 对象的
        autoPan: false, // 定义弹出窗口在边缘点击时候可能不完整 设置自动平移效果
        autoPanAnimation: {
          duration: 250, //自动平移效果的动画时间 9毫秒）
        },
      });

      // 将弹窗添加到 map 地图中
      this.map.addOverlay(this.overlay);
      let _that = this;
      /**
       * 为弹窗添加一个响应关闭的函数
       */
      closer.onclick = function () {
        _that.overlay.setPosition(undefined);
        closer.blur();
        return false;
      };
      /**
       * 添加单击map 响应函数来处理弹窗动作
       */
      this.map.on("click", function (e) {
        // let coordinate = transform(e.coordinate, "EPSG:3857", "EPSG:4326");

        let feature = _that.map.forEachFeatureAtPixel(e.pixel, function (
          feature
        ) {
          return feature;
        });

        if (feature == undefined) {
          _that.overlay.setPosition(undefined);
          closer.blur();
        } else {
          content.innerHTML = feature.get("name");
          _that.overlay.setPosition(e.coordinate); //把 overlay 显示到指定的 x,y坐标
        }

        // 点击尺 （这里是尺(米)，并不是经纬度）;
        // let hdms = toStringHDMS(toLonLat(evt.coordinate)); // 转换为经纬度显示
        // content.innerHTML = `
        // <p>你点击了这里：</p>
        // <p>经纬度：<p><code> ${hdms}  </code> <p>
        // <p>坐标：</p>X：${coordinate[0]} &nbsp;&nbsp; Y: ${coordinate[1]}`;
        // _that.overlay.setPosition(evt.coordinate); //把 overlay 显示到指定的 x,y坐标
      });
    },
    // 点击增加图标
    addIocn(con) {
      let arr = [];
      for (let i = 0; i < con.length; i++) {
        let iconFeature = new Feature({
          geometry: new Point([con[i].x, con[i].y]),
          name: `我的标识${i}`,
        });
        let src = require(`./JSON/${con[i].type}`);
        let iconStyle = new Style({
          image: new Icon({
            anchor: [0.5, 0.5],
            src: src,
          }),
        });
        iconFeature.setStyle(iconStyle);
        arr.push(iconFeature);
      }

      this.vectorLayer = new VectorLayer({
        source: new VectorSource({
          features: arr,
        }),
        zIndex: 21,
      });
      this.map.addLayer(this.vectorLayer);
    },
    //计算图表 图形
    getIcon(type) {
      let src = require(`./JSON/${type}`);
      // console.log(src);
      let styleIcon = new Style({
        // 设置图片效果
        image: new Icon({
          src: src,
          anchorXUnits: "pixels",
          anchorYUnits: "pixels",
          imgSize: [200, 200],
          anchor: [1, 1],
        }),
      });
      return styleIcon;
    },
    // 渲染JSON底层
    addJSON() {
      // =====
      let source = new VectorSource({
        features: new GeoJSON().readFeatures(JSONURl),
        wrapX: false,
      });

      let styles = new Style({
        stroke: new Stroke({
          width: 3,
          color: "pink",
        }),
        fill: new Fill({
          color: "rgba(0, 0, 255, 0.1)",
        }),
      });
      // 绘画图层
      this.vector = new VectorLayer({
        source: source,
        minZoom: 1,
        // projection: "EPSG:4326", //projection 设置地图的投影坐标系统  默认是EPSG:3857
        renderBuffer: 200,
        zIndex: 1,
        style: styles,
      });
      // console.log(fill.getColor());
      // fill.setColor("pink");
      // console.log(fill.getColor());
      // var r3D = new ol.render3D({ height: 10, defaultHeight: 3.5 });
      // this.vector.setRender3D(r3D);
      this.map.addLayer(this.vector);
    },
    // 渲染小人图层
    personIocn() {
      let arr = [];
      for (let i = 0; i < this.personIcon.length; i++) {
        let iconFeature = new Feature({
          geometry: new Point([this.personIcon[i].x, this.Icon[i].y]),
          name: `person${i}`,
        });
        let src = require(`./JSON/${this.personIcon[i].type}`);
        let iconStyle = new Style({
          image: new Icon({
            anchor: [0.5, 0.5],
            src: src,
          }),
        });
        iconFeature.setStyle(iconStyle);
        arr.push(iconFeature);
      }

      this.personLayer = new VectorLayer({
        source: new VectorSource({
          features: arr,
        }),
        zIndex: 22,
      });
      this.map.addLayer(this.personLayer);
    },
    // 跟新小人位置
    changePerson() {
      this.map.removeLayer(this.personLayer);
      for (let i = 0; i < this.personIcon.length; i++) {
        this.personIcon[i].x = this.personIcon[i].x + 500;
      }
      this.personIocn();
    },
  },
};
</script>
<style lang="scss" scoped>
.map {
  width: 100%;
  height: 90%;
}
.ol-popup {
  position: absolute;
  background-color: #ccc;
  -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  // padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
}
.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}
.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}
.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}
.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
}
.popup-content {
  width: 400px;
}
.ol-popup-closer:after {
  content: "✖";
}
#marker {
  width: 20px;
  height: 20px;
  background: red;
  border-radius: 50%;
}
#textInfo {
  width: 200px;
  height: 40px;
  line-height: 40px;
  background: burlywood;
  color: yellow;
  text-align: center;
  font-size: 20px;
}
</style>